<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻详情</title>

    <!-- 引入Vue和Axios -->
    <script src="../../js/vue.js"></script>
    <script src="../../js/axios-0.18.0.js"></script>

    <!-- 引入Element UI 样式和组件 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style>
        /*<style>*/
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 30px auto;
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .container:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .header h2 {
            font-size: 28px;
            font-weight: 700;
            color: #2c3e50;
            margin: 0;
            display: flex;
            align-items: center;
        }

        .header h2 i {
            margin-right: 10px;
            color: #409EFF;
        }

        .news-title {
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 20px;
            color: #2c3e50;
            line-height: 1.3;
            transition: color 0.3s ease;
        }

        .news-title:hover {
            color: #409EFF;
        }

        .news-meta {
            color: #7f8c8d;
            font-size: 14px;
            margin-bottom: 30px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 20px;
        }

        .news-meta div {
            display: flex;
            align-items: center;
        }

        .news-meta i {
            margin-right: 5px;
            color: #95a5a6;
        }

        .news-content {
            line-height: 1.8;
            font-size: 18px;
            margin-bottom: 40px;
            color: #333;
        }

        .news-content p {
            margin-bottom: 20px;
            text-align: justify;
        }

        .news-content h3 {
            color: #2c3e50;
            margin: 30px 0 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }

        .news-content img {
            max-width: 100%;
            height: auto;
            border-radius: 6px;
            margin: 20px 0;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        }

        .back-button {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-start;
        }

        .el-button {
            margin-right: 15px;
            transition: all 0.3s ease;
        }

        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        }

        .error-message {
            color: #e74c3c;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .error-message i {
            font-size: 32px;
            margin-right: 15px;
        }

        .loading-container {
            padding: 60px 0;
            text-align: center;
        }

        .loading-container .el-button {
            font-size: 18px;
            padding: 12px 30px;
        }

        .error-container {
            padding: 40px 0;
            text-align: center;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 15px;
                padding: 20px;
            }

            .header h2 {
                font-size: 24px;
            }

            .news-title {
                font-size: 26px;
            }

            .news-meta {
                gap: 15px;
                font-size: 13px;
            }

            .news-content {
                font-size: 16px;
            }

            .back-button {
                flex-direction: column;
            }

            .el-button {
                margin: 5px 0;
                width: 100%;
            }
        }
    </style>
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <div class="header">
            <h2>新闻详情</h2>
            <el-button type="primary" @click="goBack">返回列表</el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-button type="text" size="large" loading>加载新闻中...</el-button>
        </div>

        <!-- 新闻内容 -->
        <div v-if="!loading && news" class="news-detail">
            <div class="news-title">{{ news.title }}</div>
            <div class="news-meta">
                <div class="news-author">作者: {{ news.author || '未知' }}</div>
                <div class="news-date">发布时间: {{ formatDate(news.date) }}</div>
<!--                <div v-if="user">用户名: {{ user.username || '未知' }}</div>-->
<!--                <div v-else-if="userLoading">用户名: 加载中...</div>-->
<!--                <div v-else>用户名: 加载失败</div>-->
            </div>
            <div class="news-content" v-html="safeHtml"></div>

<!--            <div class="back-button">-->
<!--                <el-button type="primary" @click="goBack">返回列表</el-button>-->
<!--            </div>-->
        </div>

        <!-- 错误状态 -->
        <div v-if="!loading && !news" class="error-container">
            <div class="error-message" style="text-align: center; padding: 20px;">
                <i class="el-icon-error" style="font-size: 24px; margin-right: 10px;"></i>
                <span v-if="errorMsg">{{ errorMsg }}</span>
                <span v-else>新闻加载失败</span>
            </div>
            <p style="text-align: center; color: #666; margin-bottom: 20px;">
                可能是新闻ID错误、新闻已被删除或网络连接问题
            </p>
            <div style="text-align: center;">
                <el-button type="primary" @click="fetchNews">重新加载</el-button>
<!--                <el-button @click="goBack">返回列表</el-button>-->
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                news: null,
                user: null,
                loading: true,
                newsId: null,
                userLoading: false,
                errorMsg: '',
                hasUnsavedChanges: false // 标记是否有未保存的修改
            }
        },
        computed: {
            /**
             * 安全HTML渲染 - 对内容进行转义处理，防止XSS攻击
             * 实际项目中建议使用DOMPurify库进行更完善的防护
             */
            safeHtml() {
                if (this.news && this.news.context) {
                    // 简易转义处理，实际项目应使用专业库
                    return this.news.context
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#039;')
                        .replace(/&/g, '&amp;');
                }
                return '';
            }
        },
        created() {
            this.getNewsIdFromUrl();
            if (!this.newsId) {
                this.handleNewsIdMissing();
                return;
            }
            this.fetchNews();
            this.fetchUser();
        },
        methods: {
            /**
             * 从URL获取新闻ID
             * 统一使用'newsId'参数名与列表页保持一致
             */
            getNewsIdFromUrl() {
                try {
                    const urlParams = new URLSearchParams(window.location.search);
                    this.newsId = urlParams.get('newsId');
                    console.log('获取到的新闻ID:', this.newsId);
                } catch (error) {
                    console.error('解析URL参数出错:', error);
                    this.handleNewsIdMissing();
                }
            },

            /**
             * 处理新闻ID缺失的情况
             */
            handleNewsIdMissing() {
                this.errorMsg = '未找到新闻ID';
                this.loading = false;
                this.$message.error('未找到新闻ID，无法加载新闻详情');
            },

            /**
             * 获取新闻详情
             */
            fetchNews() {
                this.loading = true;
                this.errorMsg = '';

                axios.get(`http://localhost:8080/news/query/${this.newsId}`)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.news = response.data.data;
                            console.log('获取新闻详情成功:', this.news);
                        } else {
                            this.errorMsg = response.data.message || '获取新闻详情失败';
                            this.$message.error(this.errorMsg);
                        }
                    })
                    .catch(error => {
                        this.errorMsg = '获取新闻详情出错: ' + error.message;
                        console.error(this.errorMsg, error);
                        this.$message.error('网络错误，请稍后重试');
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            /**
             * 获取用户信息
             */
            fetchUser() {
                if (!this.news || !this.news.userId) return;

                this.userLoading = true;
                axios.get(`http://localhost:8080/users/findById/${this.news.userId}`)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.user = response.data.data;
                            console.log('获取用户信息成功:', this.user);
                        } else {
                            console.log('获取用户信息失败:', response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('获取用户信息出错:', error);
                    })
                    .finally(() => {
                        this.userLoading = false;
                    });
            },

            /**
             * 格式化日期
             */
            formatDate(dateStr) {
                if (!dateStr) return '未知时间';
                try {
                    const date = new Date(dateStr);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}`;
                } catch (error) {
                    console.error('日期格式化错误:', error);
                    return dateStr;
                }
            },

            /**
             * 返回新闻列表
             */
            goBack() {
                // 检查是否有未保存的修改（实际项目中根据需求实现）
                if (this.hasUnsavedChanges) {
                    this.$confirm('您有未保存的修改，确定要返回吗?', '提示', {
                        confirmButtonText: '返回',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        window.history.back();
                    }).catch(() => {
                        // 取消返回
                    });
                } else {
                    window.history.back();
                }
            }
        }
    });
</script>
</body>
</html>